package com.yixinsoft.basic.service.manage.system;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.authz.permission.WildcardPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.yixinsoft.basic.mapper.manage.system.ResourceMapper;
import com.yixinsoft.basic.model.manage.system.Resource;
import com.yixinsoft.basic.model.manage.system.ResourceType;
import com.yixinsoft.basic.model.manage.system.User;
import com.yixinsoft.basic.service.base.BaseService;

/**
 * Created by hqy on 2016/06/05
 */
@Service
public class ResourceService extends BaseService<Resource> {
	
	@Autowired
	private ResourceMapper resourceMapper;
	
	@Autowired
	private UserService userService;
	
	public Integer deleteById(Long resourceId) {
		Resource resource = queryById(resourceId);
		if (resource != null) {
			resourceMapper.deleteByParentIds(resource.makeSelfAsParentIds());
			return super.deleteById(resourceId);
		}
		return 0;
	}

	/**
     * 得到资源对应的权限字符串
     * @param resourceIds
     * @return
     */
    public Set<String> findPermissions(Set<Long> resourceIds) {
    	Set<String> permissions = new HashSet<String>();
    	for (Long resourceId : resourceIds) {
    		Resource resource = queryById(resourceId);
    		if (resource != null && !StringUtils.isEmpty(resource.getPermission())) {
    			permissions.add(resource.getPermission());
    		}
    	}
    	return permissions;
    }
    
    /**
     * 根据用户权限得到菜单
     * @param permissions
     * @return
     */
    public List<Resource> findMenus(Set<String> permissions) {
    	List<Resource> allResources = queryList(null);
    	List<Resource> menus = new ArrayList<>();
    	for (Resource resource : allResources) {
    		if (resource.isRootNode()) {
    			continue;
    		}
    		if (resource.getType() != ResourceType.menu) {
    			continue;
    		}
    		if (!hasPermission(permissions, resource)) {
    			continue;
    		}
    		menus.add(resource);
    	}
    	return menus;
    }

	private boolean hasPermission(Set<String> permissions, Resource resource) {
		if (StringUtils.isEmpty(resource.getPermission())) {
			return true;
		}
		for (String permission : permissions) {
			String[] arr = permission.split(",");
			for (String str : arr) {
				WildcardPermission p1 = new WildcardPermission(str);
				WildcardPermission p2 = new WildcardPermission(resource.getPermission());
				if (p1.implies(p2) || p2.implies(p1)) {
					return true;
				}
			}
		}
		return false;
	}
	
	public List<Resource> findMenus(User user) {
		Set<String> permissions = userService.findPermissions(user.getUsername());
		return findMenus(permissions);
	}
	
	public List<Resource> queryListOrderById() {
		return resourceMapper.queryListOrderById();
	}
}
